package com.wing.sell.controller.admin;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.sell.model.entity.AgentDue;
import com.wing.sell.model.request.AgentDueForm;
import com.wing.sell.model.response.AgentDueSubjectCategoryVO;
import com.wing.sell.model.response.AgentDueSubjectVO;
import com.wing.sell.service.AgentDueService;
import com.wing.sell.service.AgentDueSubjectCategoryService;
import com.wing.sell.service.AgentDueSubjectService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 *
 * @author
 */
@Validated
@Api(value = "Admin-代理经销商尽调记录表管理", tags = "#/sell/agentDue")
@RestController("agentDueController")
@RequestMapping("sell/admin/agentDue")
@RequiredArgsConstructor
@Slf4j
public class AgentDueController {

    private final AgentDueService agentDueService;
    private final AgentDueSubjectService agentDueSubjectService;
    private final AgentDueSubjectCategoryService agentDueSubjectCategoryService;


    @ApiOperation(value = "查询所有代理经销商尽调记录表", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "selAgtId", value = "所属代理商ID", defaultValue = "", example = "", dataType = "Long", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<AgentDue> list(
            @RequestParam(defaultValue = "1") Integer page
            ,@RequestParam(defaultValue = "10") Integer limit
            ,@RequestParam(defaultValue = "create_time") String sort
            ,@RequestParam(defaultValue = "asc") String order
            ,Long selAgtId
    ){

        Page<AgentDue> pg = new Page<>(page, limit);
        QueryWrapper<AgentDue> queryWrapper = new QueryWrapper<>();

        //排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            if (StringUtils.equals("asc", order)) {
                queryWrapper.orderByAsc(StrUtil.toUnderlineCase(sort));
            } else {
                queryWrapper.orderByDesc(StrUtil.toUnderlineCase(sort));
            }
        }

        //搜索
        if (selAgtId !=null){
            queryWrapper.eq("sel_agt_id", selAgtId);
        }

        IPage<AgentDue> list = agentDueService.getBaseMapper().selectPage(pg, queryWrapper);

        //关联相关业务属性
        list.getRecords().parallelStream().forEach(k -> {
            AgentDueSubjectCategoryVO agentDueSubjectCategoryVO = agentDueSubjectCategoryService.get4appById(k.getCategoryId());
            if(null != agentDueSubjectCategoryVO){
                k.setCategoryName(agentDueSubjectCategoryVO.getName());
            }
            AgentDueSubjectVO agentDueSubjectVO = agentDueSubjectService.get4appById(k.getSubjectId());
            if (null !=agentDueSubjectVO){
                k.setSubjectName(agentDueSubjectVO.getName());
            }
        });
        return new PageResult<>(list.getRecords(), list.getTotal());
    }



    @ApiOperation(value = "添加代理经销商尽调记录表", notes = "添加")
    @PostMapping("/add")
    public JsonResult add(@RequestBody AgentDueForm agentDueForm) {
        try{
            agentDueService.add(agentDueForm);
            return JsonResult.success("添加成功");
        }catch(Exception e){
            log.error("添加失败:", e);
            return JsonResult.fail("添加失败"+e.getMessage());
        }

    }



    @ApiOperation(value = "批量添加尽调记录表", notes = "添加")
    @PostMapping("/addList")
    public JsonResult addList(@RequestBody List<AgentDueForm> list) {
        try{
            //新添加的有重复的分类和科目 不让添加
            Set<HashMap> s = new HashSet<>();
            for(AgentDueForm agentDueForm:list){
                s.add(new HashMap(){{put(agentDueForm.getCategoryId(),agentDueForm.getSubjectId());}});
            }
            if (s.size()!=list.size()){
                return JsonResult.fail("添加的尽调分类和尽调科目存在重复,请删除重复项后再保存");
            }

            //查询该已经添加过的尽调信息  分类和科目
            List<AgentDue> agentDues =agentDueService.list(new QueryWrapper<AgentDue>().eq("sel_agt_id",list.get(0).getSelAgtId()));
            if (agentDues!=null){
                for (AgentDue agentDue:agentDues){
                    for(AgentDueForm agentDueForm:list){
                        if (agentDue.getCategoryId()==agentDueForm.getCategoryId()&&agentDue.getSubjectId()==agentDueForm.getSubjectId()){
                            //有重复的不让添加
                            return JsonResult.fail("分类:    "+agentDueSubjectCategoryService.get4appById(agentDue.getCategoryId()).getName()+"   科目:    "+agentDueSubjectService.get4appById(agentDue.getSubjectId()).getName()+"   已添加,请勿重复添加");
                        }
                    }
                }
            }

            for(AgentDueForm agentDueForm:list){
                agentDueService.add(agentDueForm);
            }
            return JsonResult.success("添加成功！");
        }catch(Exception e){
            log.error("添加失败！",e);
            return JsonResult.fail("添加失败！"+e.getMessage());
        }
    }




    @ApiOperation(value = "修改代理经销商尽调记录表", notes = "修改")
    @PutMapping("/update")
    public JsonResult update(@RequestBody AgentDueForm agentDueForm) {
        try {
            agentDueService.update(agentDueForm);
            return JsonResult.success("修改成功！");
        }catch(Exception e){
            log.error("修改失败！",e);
            return JsonResult.fail("修改失败！"+e.getMessage());
        }
    }



    @ApiOperation(value = "删除代理经销商尽调记录表", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "agentDueId", value = "代理经销商尽调记录表id", required = true, dataType = "Integer", paramType = "path")
    })
    @DeleteMapping("/{id}" )
    public JsonResult delete(@PathVariable("id") Long agentDueId) {
        if (agentDueService.removeById(agentDueId)) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }

    @ApiOperation(value = "审核", notes = "审核")
    @PutMapping("/check")
    public JsonResult check(@RequestBody AgentDueForm agentDueForm) {
        try{
            agentDueService.check(agentDueForm);
            return JsonResult.success("审核成功！");
        }catch (Exception e){
            log.error("审核失败！", e);
            return JsonResult.fail("审核失败！" + e.getMessage());
        }
    }
}
